#include <stdio.h>
#include <stdlib.h>
#include "rate_list.h"


int init_rate_list(rate_t *prate, time_t duration, int unit_type)
{
	prate->index = 0;
	prate->unit_type = unit_type;
	switch(unit_type)
	{
		case	RATE_UNIT_SECOND:
			prate->array_size = (unsigned int)duration + 1;
			prate->interval = 1;
			break;
		case	RATE_UNIT_MINUTE:
			prate->array_size = (unsigned int)(duration/60) + 1;
			prate->interval = 60;
			break;
		case	RATE_UNIT_HOUR:
			prate->array_size = (unsigned int)(duration/(60*60)) + 1;
			prate->interval = 60*60;
			break;
		default:
			return -2;
	}
	if(prate->rate_array)
	{
		free(prate->rate_array);
	}
	prate->rate_array = calloc(prate->array_size, sizeof(rate_node_t));
	if(!prate->rate_array)
	{
		return -1;
	}

	return 0;
}

int start_rate_count(rate_t *prate, int value)
{
	gettimeofday(&prate->rate_array[prate->index].cur_time, NULL);
	prate->rate_array[prate->index].value += value;
	return prate->index;
}

int step_rate_count(rate_t *prate, int value)
{
	prate->index ++;
	if(prate->index >= prate->array_size)
	{
		return -1;
	}
	gettimeofday(&prate->rate_array[prate->index].cur_time, NULL);
	prate->rate_array[prate->index].value += value;
	return prate->index;
}

void add_rate_count(rate_t *prate, int value)
{
	prate->rate_array[prate->index].value += value;
}

int end_rate_count(rate_t *prate, int value)
{
	gettimeofday(&prate->rate_array[prate->index].cur_time, NULL);
	prate->rate_array[prate->index].value += value;
	return prate->index;
}

int exit_rate_list(rate_t *prate)
{
	if(prate->rate_array)
	{
		free(prate->rate_array);
	}
	return 0;
}
